package com.wangjie.service.impl;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.URLUtil;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.wangjie.dao.SysFileMapper;
import com.wangjie.exception.BusinessException;
import com.wangjie.pojo.SysFile;
import com.wangjie.service.SysFileService;
import com.wangjie.text.Convert;
import com.wangjie.utils.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @author jieshao
 * @date 2021/11/23 16:24
 */
@Service
public class SysFileServiceImpl implements SysFileService {
    private Logger logger = LoggerFactory.getLogger(SysFileServiceImpl.class);

    @Autowired
    private SysFileMapper fileMapper;

    @Autowired
    private FastFileStorageClient storageClient;

    @Override
    public List<SysFile> selectFileList(SysFile file) {
        return fileMapper.selectFileList(file);
    }

    @Override
    public SysFile selectById(Integer id) {
        return fileMapper.selectByPrimaryKey(id);
    }

    @Override
    public int deleteByIds(String ids) {
        String[] arr = Convert.toStrArray(ids);
        List<SysFile> list = fileMapper.selectByIds(arr);
        for (SysFile file : list) {
            String filePath = file.getFilePath();
            StorePath storePath = StorePath.parseFromUrl(filePath);
            storageClient.deleteFile(storePath.getGroup(), storePath.getPath());
        }
        return fileMapper.deleteByIds(arr);
    }

    @Override
    public int upload(MultipartFile file) throws Exception {
        String fileName = file.getOriginalFilename();
        String fileSuffix = FilenameUtils.getExtension(fileName);
        long size = file.getSize();

        StorePath storePath = storageClient.uploadFile(file.getInputStream(), size, fileSuffix, null);
        String filePath = storePath.getFullPath();
        String fileSize = FileUtils.getSize(size);
        String fileType = FileUtils.getFileType(fileSuffix);

        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String createTime = LocalDateTime.now().format(dtf);

        SysFile sysFile = new SysFile();
        sysFile.setFileName(fileName.substring(0, fileName.lastIndexOf(".")));
        sysFile.setFileSuffix(fileSuffix);
        sysFile.setFileType(fileType);
        sysFile.setFileSize(fileSize);
        sysFile.setFilePath(filePath);
        sysFile.setCreateTime(createTime);

        return fileMapper.insertSelective(sysFile);
    }

    @Override
    public void download(Integer id, HttpServletResponse response) {
        SysFile file = fileMapper.selectByPrimaryKey(id);
        String fileName = file.getFileName() + "." + file.getFileSuffix();
        String filePath = file.getFilePath();
        StorePath storePath = StorePath.parseFromUrl(filePath);
        try {
            byte[] buffer = storageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadByteArray());
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=" + URLUtil.encode(fileName, "UTF-8"));
            response.addHeader("Content-Length", "" + buffer.length);
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            response.setContentType("application/octet-stream;charset=UTF-8");
            IoUtil.write(response.getOutputStream(), true, buffer);
        } catch (Exception e) {
            logger.error("下载文件异常, 异常信息为：{}", e.getMessage());
            throw new BusinessException("下载文件异常");
        }
    }

    @Override
    public void view(Integer id, HttpServletResponse response) {
        SysFile file = fileMapper.selectByPrimaryKey(id);
        String filePath = file.getFilePath();
        StorePath storePath = StorePath.parseFromUrl(filePath);
        try {
            byte[] buffer = storageClient.downloadFile(storePath.getGroup(), storePath.getPath(), new DownloadByteArray());
            response.setContentType(MediaType.IMAGE_JPEG_VALUE);
            IoUtil.write(response.getOutputStream(), true, buffer);
        } catch (Exception e) {
            logger.error("预览文件异常, 异常信息为：{}", e.getMessage());
            throw new BusinessException("预览文件异常");
        }
    }
}